% 绘制匀速运动电荷的电磁场
% 使用AI辅助
% Gitee Repo

% 清除工作区和命令窗口
clc;
clear;

% 定义网格参数
L = 1;
dx = 0.2;

% 创建三维网格
[x, y, z] = meshgrid(-L:dx:L, -L:dx:L, -L:dx:L);

v = 0.8;%速度
t = 0;
gamma = 1 / sqrt(1 - v^2);% 相对论因子 gamma

figure;

for t = -1:0.1:1
    % 计算距离平方和距离
    R2 = (x-v*t).^2 + y.^2 + z.^2;
    R = sqrt(R2);

    % 计算 cos^2 和 sin^2
    cos2 = ((x-v*t).^2) ./ R2;
    sin2 = 1 - cos2;

    % 计算系数 coeff
    coeff = 0.1 ./ (gamma^2 * (1 - v^2 * sin2)) ./ R.^3;

    % 处理无效值
    coeff(isnan(coeff) | isinf(coeff)) = 0;
    coeff(coeff > 1) = 1;
    coeff(coeff < -1) = -1;

    % 计算电场分量
    coeff(abs(coeff) < 0.05) = 0;
    Ex = coeff .* (x-v*t);
    Ey = coeff .* y;
    Ez = coeff .* z;

    % 计算磁场分量
    Bx = zeros(size(Ex));
    By = -v*Ez;
    Bz = v*Ey;

    % 绘制结果
    clf
    hold on;
    axis equal;
    axis([-L,L,-L,L,-L,L])

    quiver3(x, y, z, Ex, Ey, Ez, 0);
    quiver3(x, y, z, Bx, By, Bz, 0);

    title('匀速电荷的电磁场');
    xlabel('X-axis');
    ylabel('Y-axis');
    zlabel('Z-axis');
    scatter3(v*t,0,0,'r')
    %legend('Electric Field', 'Magnetic Field');

    drawnow
    pause(0.1)
end

